using System;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;
using System.Drawing.Drawing2D;

namespace GoogleEarthClasses.Global
{
    public class GImages
    {
        /// <summary>
        /// Resize a byte image
        /// </summary>
        /// <param name="imageFile">Source Image</param>
        /// <param name="targetSize">Width</param>
        /// <returns></returns>
        public static byte[] ResizeImageFile(byte[] imageFile, int targetSize)
        {
            Image original = null;
            Image imgPhoto = null;
            Bitmap bmPhoto = null;
            Graphics grPhoto = null;
            MemoryStream mm = null;
            try
            {
                original = Image.FromStream(new MemoryStream(imageFile));
                int targetH, targetW;
                if (original.Height > original.Width)
                {
                    targetH = targetSize;
                    targetW = (int)(original.Width * ((float)targetSize / (float)original.Height));
                }
                else
                {
                    targetW = targetSize;
                    targetH = (int)(original.Height * ((float)targetSize / (float)original.Width));
                }
                imgPhoto = Image.FromStream(new MemoryStream(imageFile));
                // Create a new blank canvas.  The resized image will be drawn on this canvas.
                bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb);
                bmPhoto.SetResolution(72, 72);
                grPhoto = Graphics.FromImage(bmPhoto);
                grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
                grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
                grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
                grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel);
                // Save out to memory and then to a file.  We dispose of all objects to make sure the files don't stay locked.
                mm = new MemoryStream();
                bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
                return mm.GetBuffer();
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                original.Dispose();
                imgPhoto.Dispose();
                bmPhoto.Dispose();
                grPhoto.Dispose();
                mm.Close();
                mm.Dispose();
            }
        }
        /// <summary>
        /// Create a thumbail image.
        /// </summary>
        /// <param name="ImageBuffer">source image</param>
        /// <param name="thumbWidth">prefered thumbail width</param>
        /// <param name="thumbHeight">prefered thumbail heigth</param>
        /// <returns></returns>
        public static byte[] Generate_ThumbailImage(byte[] ImageBuffer,int thumbWidth, int thumbHeight)
        {
            FileStream _ms = null;
            Image _DatabaseImage;
            Image _Thumbail;
            Image _tmpImage;
            try
            {
                SaveImage(ImageBuffer, "C:\\testing.jpeg");
                _ms = File.Open("C:\\testing.jpeg", FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
                _tmpImage = Image.FromStream(_ms);
                _ms.Close();
                _ms.Dispose();
                _DatabaseImage = (Image)_tmpImage.Clone();
                _tmpImage.Dispose();
                
                if (_DatabaseImage.Width < thumbWidth && _DatabaseImage.Height < thumbHeight)
                {
                    _Thumbail = _DatabaseImage.GetThumbnailImage(_DatabaseImage.Width, _DatabaseImage.Height, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
                }
                else
                {
                    #region GET IDEAL THUMB SIZE
                    double thumbRatio = (double)thumbWidth / (double)thumbHeight;
                    int imageWidth = _DatabaseImage.Width;
                    int imageHeight = _DatabaseImage.Height;
                    double imageRatio = (double)imageWidth / (double)imageHeight;
                    if (thumbRatio < imageRatio)
                        thumbHeight = (int)(thumbWidth / imageRatio);
                    else
                        thumbWidth = (int)(thumbHeight * imageRatio);
                    #endregion GET IDEAL THUMB SIZE
                    _Thumbail = _DatabaseImage.GetThumbnailImage(thumbWidth, thumbHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
                }
                MemoryStream _ms2 = new MemoryStream();
                _Thumbail.Save(_ms2, ImageFormat.Jpeg);
                return _ms2.ToArray();
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                _ms.Close();
            }
        }

        private static bool ThumbnailCallback()
        {
            return true;
        }

        /// <summary>
        /// Save the byte image into local disk
        /// </summary>
        /// <param name="ImageBuffer">source Image</param>
        /// <param name="FileName">Fullpath where save the image</param>
        /// <returns>True if succesful</returns>
        public static bool SaveImage(byte[] ImageBuffer, string FileName)
        {
            Bitmap b = null;
            MemoryStream ms = null;
            try
            {
                ms = new MemoryStream(ImageBuffer, 0, ImageBuffer.Length);
                b = new Bitmap(ms);
                b.Save(FileName, ImageFormat.Jpeg);
                return true;

            }
            catch (Exception)
            {
                return false;
                throw;
            }
            finally
            {
                ms.Close();
                b.Dispose();
            }
        
        }

        /// <summary>
        /// Crate a image from bytes, and save in the Image-Cache folders
        /// </summary>
        /// <param name="ImageBytes">source image</param>
        /// <param name="ImageName">ImageName</param>
        /// <returns></returns>
        public static string CreateImageFromBytes(byte[] ImageBytes, string ImageName)
        {
            MemoryStream ms = null;
            Image Photo = null;

            if (!Directory.Exists(Constants.k_PathSaveImages))
                Directory.CreateDirectory(Constants.k_PathSaveImages);
            try
            {
                string DestinationPath = Constants.k_PathSaveImages + ImageName;
                ms = new MemoryStream(ImageBytes, 0, ImageBytes.Length);
                Photo = Image.FromStream(ms);
                Photo.Save(DestinationPath);
                return DestinationPath;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                ms.Close();
                Photo.Dispose();
            }


        }

        /// <summary>
        /// get the correct image-Cache sub direcotry  to save the image
        /// </summary>
        /// <param name="PositionId"></param>
        /// <returns></returns>
        public static string CheckingImageFolder(int PositionId)
        {
            int Start = 0;
            int End = 99;
            string _Directory = "";
            try
            {
                while (_Directory == "")
                {
                    if (PositionId > Start && PositionId > End)
                    {
                        Start += 100;
                        End += 100;
                    }
                    else
                    {
                        _Directory = Start.ToString() + "-" + End.ToString();
                        DirHelper.isDirectory(Constants.K_ImageCachePath + _Directory);
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
            return _Directory;
        }

        public static byte[] ConvertImageToByteArray(Image imageToConvert, ImageFormat formatOfImage)
        {
            byte[] Ret;

            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    imageToConvert.Save(ms, formatOfImage);
                    Ret = ms.ToArray();
                }
            }
            catch (Exception) { throw; }

            return Ret;
        } 
    }
}